const Koa = require('koa');
const KoaRouter = require('koa-router');

const server = new Koa();
const router = new KoaRouter();

// 生成签名字符串所使用的秘钥
server.keys = ['kkb'];

router.get('/user', async (ctx, next) => {

    let user = null;

    try {
        user = ctx.cookies.get('user',  {
            // 是否验证当前cookie的签名正确性
            signed: true
        });
    } catch (e) {
        ctx.throw(401, '没有权限');
    }

    if (!user) {
        ctx.throw(401, '没有权限');
    } else {
        ctx.body = '大海和小蕊';
    }

});

router.post('/login', async (ctx, next) => {
    let user = {
        id: 1,
        username: 'zMouse'
    };
    // 设置cookie
    ctx.cookies.set('user', JSON.stringify(user), {
        // 是否同时生成签名
        signed: true
    });

    // 设置多个cookie
    // ctx.cookies.set('a', 1);
    // ctx.cookies.set('b', 2);

    ctx.body = '授权成功';
})

server.use(router.routes());

server.listen(8888);
